package com.mornd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mornd.entity.Menu;
import com.mornd.mapper.MenuMapper;
import com.mornd.service.MenuService;
import com.mornd.vo.MenuVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.List;


/**
 * @author mornd
 * @date 2021/1/7 - 1:00
 */
@Service
@Transactional(readOnly = true,rollbackFor = Exception.class)
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    /**
     * 根据用户id查询该用户对应的角色
     *
     * @param userId
     * @return
     */
    @Override
    public List<Menu> findByUserId(Integer userId) {
        return getBaseMapper().findByUserId(userId);
    }

    /**
     * 查询简单列
     *
     * @return
     */
    @Override
    public List<Menu> getSimpleMenus() {
        return getBaseMapper().getSimpleMenus();
    }

    /**
     * 根据条件查询menu集合
     *
     * @param menuVo
     * @return
     */
    @Override
    public IPage<Menu> findList(MenuVo menuVo) {
        //分页信息
        IPage<Menu> page = new Page<>(menuVo.getPage(),menuVo.getLimit());
        //查询条件
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.like(!ObjectUtils.isEmpty(menuVo.getTitle()),"title",menuVo.getTitle());
        wrapper.like(!ObjectUtils.isEmpty(menuVo.getCode()),"code",menuVo.getCode());
        boolean condition = ObjectUtils.isEmpty(menuVo.getId());
        wrapper.eq(!condition,"id",menuVo.getId())
                .or().eq(!condition,"pid",menuVo.getId());
        //排序
        wrapper.orderByAsc("pid");
        return super.page(page,wrapper);
    }

    /**
     * 查看该菜单下是否有子菜单
     *
     * @param menuId
     * @return
     */
    @Override
    public int checkHasChildrenNode(Integer menuId) {
        return getBaseMapper().checkHasChildrenNode(menuId);
    }

    /**
     * 超级管理员自动添加全部菜单权限
     *
     * @param roleId
     * @param menuId
     * @return
     */
    @Override
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public int addMenuBySuperA(Integer roleId, Integer menuId) {
        return getBaseMapper().addMenuBySuperA(roleId,menuId);
    }

    /**
     * 根据 ID 删除
     * 删除角色菜单表数据
     * @param id 主键ID
     */
    @Override
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        //删除角色菜单关系表数据
        getBaseMapper().deleteRelationByMenuId(id);
        return super.removeById(id);
    }
}
